import 'package:flutter/material.dart';
import '../models/product.dart';
import '../models/cart_item.dart';

class NewSaleSection extends StatefulWidget {
  const NewSaleSection({Key? key}) : super(key: key);

  @override
  State<NewSaleSection> createState() => _NewSaleSectionState();
}

class _NewSaleSectionState extends State<NewSaleSection> {
  final List<CartItem> _cartItems = [];
  double _totalAmount = 0.0;
  final TextEditingController _searchController = TextEditingController();

  // ۋاقىتلىق مەھسۇلات تىزىملىكى (كېيىن مەلۇمات ئامبىرىدىن ئېلىنىدۇ)
  final List<Product> _products = [
    Product(
      id: '1',
      name: 'ئالما',
      price: 5.99,
      stock: 100,
      unit: 'كىلو',
      category: 'مېۋە',
    ),
    Product(
      id: '2',
      name: 'ئۈزۈم',
      price: 8.99,
      stock: 80,
      unit: 'كىلو',
      category: 'مېۋە',
    ),
    Product(
      id: '3',
      name: 'پىياز',
      price: 3.99,
      stock: 150,
      unit: 'كىلو',
      category: 'كۆكتات',
    ),
  ];

  List<Product> _filteredProducts = [];

  @override
  void initState() {
    super.initState();
    _filteredProducts = _products;
    _searchController.addListener(_filterProducts);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _filterProducts() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredProducts = _products.where((product) {
        return product.name.toLowerCase().contains(query) ||
               product.category.toLowerCase().contains(query);
      }).toList();
    });
  }

  void _addToCart(Product product) {
    setState(() {
      final existingItem = _cartItems.firstWhere(
        (item) => item.product.id == product.id,
        orElse: () => CartItem(product: product, quantity: 0),
      );

      if (existingItem.quantity == 0) {
        _cartItems.add(CartItem(product: product, quantity: 1));
      } else {
        existingItem.incrementQuantity();
      }
      _updateTotalAmount();
    });
  }

  void _removeFromCart(CartItem item) {
    setState(() {
      if (item.quantity > 1) {
        item.decrementQuantity();
      } else {
        _cartItems.remove(item);
      }
      _updateTotalAmount();
    });
  }

  void _updateTotalAmount() {
    _totalAmount = _cartItems.fold(
      0,
      (sum, item) => sum + item.total,
    );
  }

  void _showPaymentDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('تۆلەش ئۇسۇلىنى تاللاڭ'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.money),
              title: const Text('نەق پۇل'),
              onTap: () {
                Navigator.pop(context);
                _processPayment('cash');
              },
            ),
            ListTile(
              leading: const Icon(Icons.credit_card),
              title: const Text('كارتا'),
              onTap: () {
                Navigator.pop(context);
                _processPayment('card');
              },
            ),
            ListTile(
              leading: const Icon(Icons.account_balance_wallet),
              title: const Text('ئېلېكترونلۇق ھەمياندىن'),
              onTap: () {
                Navigator.pop(context);
                _processPayment('wallet');
              },
            ),
          ],
        ),
      ),
    );
  }

  void _processPayment(String paymentMethod) {
    // تۆلەش مۇۋەپپەقىيەتلىك بولغاندىن كېيىن
    setState(() {
      _cartItems.clear();
      _totalAmount = 0;
    });
    
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('تۆلەش مۇۋەپپەقىيەتلىك بولدى'),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          TextField(
            controller: _searchController,
            decoration: InputDecoration(
              hintText: 'مال ئىزدەش...',
              prefixIcon: const Icon(Icons.search),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          ),
          const SizedBox(height: 16),
          
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  flex: 2,
                  child: Card(
                    child: ListView.builder(
                      itemCount: _filteredProducts.length,
                      itemBuilder: (context, index) {
                        final product = _filteredProducts[index];
                        return ListTile(
                          title: Text(product.name),
                          subtitle: Text('${product.category} - ${product.stock} ${product.unit} بار'),
                          trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                '¥${product.price.toStringAsFixed(2)}',
                                style: const TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                ),
                              ),
                              const SizedBox(width: 8),
                              IconButton(
                                icon: const Icon(Icons.add_shopping_cart),
                                onPressed: () => _addToCart(product),
                                color: Colors.orange,
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ),
                
                const SizedBox(width: 16),
                
                Expanded(
                  child: Card(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Padding(
                            padding: EdgeInsets.all(8.0),
                            child: Text(
                              'سېتىۋېلىش سېۋىتى',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                          const Divider(),
                          Expanded(
                            child: ListView.builder(
                              itemCount: _cartItems.length,
                              itemBuilder: (context, index) {
                                final item = _cartItems[index];
                                return ListTile(
                                  title: Text(item.product.name),
                                  subtitle: Text(
                                    '${item.quantity} × ¥${item.product.price.toStringAsFixed(2)}',
                                  ),
                                  trailing: Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      Text(
                                        '¥${item.total.toStringAsFixed(2)}',
                                        style: const TextStyle(fontWeight: FontWeight.bold),
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.remove_circle_outline),
                                        onPressed: () => _removeFromCart(item),
                                        color: Colors.red,
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'جەمئىي سومما:',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  Text(
                    '¥${_totalAmount.toStringAsFixed(2)}',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Theme.of(context).primaryColor,
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: SizedBox(
              width: double.infinity,
              height: 50,
              child: ElevatedButton(
                onPressed: _cartItems.isEmpty ? null : _showPaymentDialog,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.orange,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: const Text(
                  'تۆلەش',
                  style: TextStyle(fontSize: 18),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
} 